package com.yonder.hashmaptest;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 
 * 2018年9月15日
 * 
 */
public class MyPeriodHashMap<V> implements Map<Long, V> {
	
    private static long period = 1;
    /** 设置区间, 使用之前要调用一下
     * @param period longkey的区间如1001,2001...9001
     */
    public static void setPeriod(long period) {
    	MyPeriodHashMap.period = period;
    }

	private HashMap<Key, V> map = new HashMap<>();
	
	static class Key {
		long kVal;
		/**
		 * 
		 */
		public Key(long key) {
			this.kVal = key;
		}
		@Override
		public int hashCode() {
			return Long.hashCode(kVal / period);
		}
		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			Key other = (Key) obj;
			if (kVal != other.kVal)
				return false;
			return true;
		}
		public static Key valueOf(long key) {
			return new Key(key);
		}
	}
    public V put(long key, V value) {
        return map.put(Key.valueOf(key), value);
    }
	public V get(long key) {
        return map.get(Key.valueOf(key));
    }
	@Override
	public int size() {
		return map.size();
	}
	@Override
	public boolean isEmpty() {
		return map.isEmpty();
	}
	@Override
	public boolean containsKey(Object key) {
		return map.containsKey(objectToKey(key));
	}
	@Override
	public boolean containsValue(Object value) {
		return map.containsValue(value);
	}
	@Override
	public V get(Object key) {
		return get(objectToKey(key));
	}

    private long objectToKey(Object key) {
        return (long) ((Long) key).longValue();
    }
	@Override
	public V put(Long key, V value) {
		return put(objectToKey(key), value);
	}
	@Override
	public V remove(Object key) {
		return map.remove(objectToKey(key));
	}
	@Override
	public void putAll(Map<? extends Long, ? extends V> m) {
        throw new UnsupportedOperationException();
	}
	@Override
	public void clear() {
		map.clear();
	}
	@Override
	public Set<Long> keySet() {
        throw new UnsupportedOperationException();
	}
	public Set<Key> myKeySet() {
        return map.keySet();
	}
	@Override
	public Collection<V> values() {
		return map.values();
	}
	@Override
	public Set<java.util.Map.Entry<Long, V>> entrySet() {
        throw new UnsupportedOperationException();
	}
	public Set<Map.Entry<Key, V>> myEntrySet() {
		return map.entrySet();
	}
}
